package cn.j0n4than.api.controller.api.user;

import cn.j0n4than.api.config.ResponseConfig;
import cn.j0n4than.api.entity.Auth;
import cn.j0n4than.api.entity.User;
import cn.j0n4than.api.entity.pojo.UserProfilePojo;
import cn.j0n4than.api.utils.BcryptUtil;
import cn.j0n4than.api.utils.MailUtil;
import cn.j0n4than.api.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jonathan
 */
@RestController
@RequestMapping("/api/user")
public class UserHomeController extends UserBaseController {

    @Autowired
    MailUtil mailUtil;

    @GetMapping({"/", "/home"})
    public Response home() {
        return Response.success().setMessage("home");
    }

    @GetMapping("/mail_test")
    public Response mailTest() {
        mailUtil.send("userTest", "2213147257@qq.com", "admin@56fkj.cn", "userTestContent");
        return Response.success();
    }

    @PostMapping("/profile")
    public Response profile(HttpServletRequest request, @Validated @RequestBody UserProfilePojo userProfilePojo, BindingResult bindingResult) {
        Response response = Response.response();
        response.setStatus(ResponseConfig.ERROR);

        //获取验证器错误
        if (bindingResult.hasErrors()) {
            assert bindingResult.getFieldError() != null;
            String message = bindingResult.getFieldError().getDefaultMessage();
            return response.setMessage(message);
        }

        //获取这个请求的用户信息
        User user = this.getCurrentUser((Auth) request.getAttribute("auth"));

        //验证旧密码和两次输入的新密码是否一致
        if (!BcryptUtil.passwordVerify(userProfilePojo.oldPassword, user.password)) {
            response.setMessage("旧密码不正确");
        } else if (!userProfilePojo.newPassword.equals(userProfilePojo.conPassword)) {
            response.setMessage("两次输入的密码不一致");
        } else {
            user.password = BcryptUtil.passwordHash(userProfilePojo.newPassword);
            if (userService.update(user.id, user) > 0) {
                response.setStatus(ResponseConfig.SUCCESS).setMessage("修改密码成功");
            }
        }

        return response;
    }

    @GetMapping("/getCurrentUserInfo")
    public Response getCurrentUserInfo(HttpServletRequest request) {
        Response response = Response.response();

        User currentUser = this.getCurrentUser((Auth) request.getAttribute("auth"));
        currentUser.password = null;

        response.setStatus(ResponseConfig.SUCCESS);
        response.setMessage("success");
        response.setResult("user", currentUser);
        return response;
    }
}
